package com.gitee.wsl.android.cli


import android.content.Context
import android.system.Os
import java.io.Closeable
import java.io.File
import java.util.UUID

class ProcessEnv constructor(
    context: Context,
    builder: ProcessBuilder,
    knownHosts: String?,
) : Closeable {
    val home = File(context.cacheDir, UUID.randomUUID().toString())
    val pathDir = File(context.cacheDir, UUID.randomUUID().toString())

    init {
        home.mkdir()
        pathDir.mkdir()

        val sshDir =
            File(home, ".ssh").apply {
                this.mkdir()
            }

        val srcKey = Utils.privateKeyFile(context)

        if (srcKey.exists()) {
            srcKey.copyTo(File(sshDir, "id_dropbear"))
        }

        if (knownHosts != null) {
            val knownHostsFile = File(sshDir, "known_hosts")
            knownHostsFile.writeText(knownHosts)
        }

        Os.symlink(
            "${context.applicationInfo.nativeLibraryDir}/libdbclient.so",
            "${pathDir.path}/ssh",
        )

        val env = builder.environment()
        env["HOME"] = home.path
        env["PATH"] = "${pathDir.path}:${env["PATH"]}"
    }

    override fun close() {
        home.deleteRecursively()
        pathDir.deleteRecursively()
    }
}

class Utils {
    companion object {
        const val ERROR_NO_PRIVATE_KEY = 100
        const val ERROR_MISSING_STORAGE_PERMISSION = 101
        const val KEY_FILENAME = "id_dropbear"

        fun privateKeyFile(context: Context): File {
            return File(context.filesDir, KEY_FILENAME)
        }
    }
}